<template>
  <div id="userManagePage">
    <a-flex justify="space-between">
      <h2 style="margin-left: 100px">用户管理</h2>
      <a-space style="margin-right: 100px">
        <a-button
          type="primary"
          href="/user/register"
          :icon="h(UserAddOutlined)"
          title="新增用户（管理员）"
        >
          新增用户
        </a-button>
      </a-space>
    </a-flex>
    <div style="margin-bottom: 12px" />
    <!-- 用户搜索表单 -->
    <a-form layout="inline" :model="searchParams">
      <div class="userSearchForm">
        <a-form-item label="用户Id" class="userId">
          <a-input
            v-model:value="searchParams.id"
            placeholder="精确搜索"
            allow-clear
            @change="doSearch"
          />
        </a-form-item>
        <a-form-item label="账号">
          <a-input
            v-model:value="searchParams.userAccount"
            placeholder="模糊搜索"
            allow-clear
            @change="doSearch"
          />
        </a-form-item>
        <a-form-item label="关键词">
          <a-input
            v-model:value="searchParams.searchText"
            placeholder="用户昵称或个性签名"
            allow-clear
            @change="doSearch"
          />
        </a-form-item>
        <a-form-item label="身份">
          <a-auto-complete
            v-model:value="searchParams.userRole"
            placeholder="user/admin/vip/svip"
            :options="userRoleOptions"
            style="min-width: 180px"
            allow-clear
            @change="doSearch"
          />
        </a-form-item>
      </div>
    </a-form>
    <div style="margin-bottom: 16px" />
    <!-- 用户数据表单 -->
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="doTableChange"
      :scroll="{ x: 1000, y: 480 }"
      :loading="loading"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'userAvatar'">
          <a-image :src="record.userAvatar" style="width: 75px" />
        </template>
        <template v-else-if="column.dataIndex === 'userRole'">
          <div v-if="record.userRole === 'admin'">
            <a-tag color="#ffbf00">管理员</a-tag>
          </div>
          <div v-if="record.userRole === 'user'">
            <a-tag color="blue">普通用户</a-tag>
          </div>
          <div v-if="record.userRole === 'vip'">
            <a-tag color="#E4080A" style="opacity: 71%">会员</a-tag>
          </div>
          <div v-if="record.userRole === 'svip'">
            <a-tag color="#9348A8">超级会员</a-tag>
          </div>
        </template>
        <template v-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space wrap>
            <a-button
              :icon="h(EditOutlined)"
              type="primary"
              @click="doEdit(record.id)"
              title="编辑用户信息"
              >编辑
            </a-button>
            <!-- 删除用户 气泡确认框 -->
            <a-popconfirm
              title="确定删除该用户吗？"
              ok-text="确认"
              cancel-text="取消"
              @confirm="doDelete(record.id)"
              @cancel="cancelDelete"
            >
              <a href="#">
                <a-button
                  :icon="h(DeleteOutlined)"
                  type="primary"
                  danger
                  style="opacity: 93%"
                  title="删除用户"
                >
                  删除
                </a-button>
              </a>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>
  </div>
</template>
<script lang="ts" setup>
import { computed, onMounted, reactive, ref, h } from 'vue'
import {
  deleteUserUsingPost,
  listMaskedUserVoByPageUsingPost,
  listUserRoleUsingGet,
} from '@/api/userController.ts'
import { message } from 'ant-design-vue'
import { EditOutlined, DeleteOutlined, UserAddOutlined } from '@ant-design/icons-vue'

import dayjs from 'dayjs'

// 用户管理表格第一行信息
const columns = [
  {
    title: '用户ID',
    dataIndex: 'id',
    width: 190,
  },
  {
    title: '账号',
    dataIndex: 'userAccount',
    width: 210,
  },
  {
    title: '昵称',
    dataIndex: 'userName',
    width: 210,
  },
  {
    title: '头像',
    dataIndex: 'userAvatar',
    width: 150,
  },
  {
    title: '个性签名',
    dataIndex: 'userProfile',
    ellipsis: true,
    width: 220,
  },
  {
    title: '身份',
    dataIndex: 'userRole',
    width: 155,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 215,
  },
  {
    title: '操作',
    key: 'action',
  },
]

// 定义数据类型
const dataList = ref<API.MaskedUserVO[]>([])

// 分页数据总数
const total = ref(0)

// 定义搜索条件
const searchParams = reactive<API.UserQueryRequest>({
  current: 1,
  pageSize: 15,
  sortField: '',
  sortOrder: 'ascend',
})
const loading = ref(true)
// 根据搜索条件，远程获取数据
const fetchData = async () => {
  loading.value = true
  const res = await listMaskedUserVoByPageUsingPost({
    // ... 是展开运算符，它主要用于将 searchParams 对象中的所有可枚举属性展开并合并到另一个对象中，
    // 从而保证 searchParams 不会受到 fetchData 函数内其他操作的污染
    ...searchParams,
  })
  if (res.data.code === 0 && res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取用户数据失败，' + res.data.message)
  }
  loading.value = false
}

// 首次进入用户管理页面，请求一次默认搜索的用户数据
onMounted(() => {
  fetchData()
})

// 定义分页器参数
const pagination = computed(() => {
  return {
    current: searchParams.current,
    pageSize: searchParams.pageSize,
    total: total.value,
    showSizeChange: true,
    // @ts-ignore
    showTotal: (total) => `共 ${total} 条`,
  }
})

// 改变分页展示
const doTableChange = (page: any) => {
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  // 重新获取数据
  fetchData()
}

// 搜索用户数据
const doSearch = () => {
  // 重置页码 搜索结束回到第一页
  searchParams.current = 1
  fetchData()
}

// 根据身份搜索默认列表
const userRoleOptions = ref<String[]>([])

/**
 * 进入用户管理页面 根据身份搜索默认搜索词列表
 */
const getUserRoleOptions = async () => {
  const res = await listUserRoleUsingGet()
  if (res.data.code === 0 && res.data.data) {
    // @ts-ignore
    userRoleOptions.value = (res.data.data.userRoleList ?? []).map((data: String) => {
      return {
        value: data,
        label: data,
      }
    })
  } else {
    message.error('用户管理页面有误，' + res.data.message)
  }
}

onMounted(() => {
  getUserRoleOptions()
})

// 删除用户
const doDelete = async (id: String) => {
  // 前端校验一下id是否有效
  if (!id) {
    return
  }
  // @ts-ignore
  const res = await deleteUserUsingPost({ id })
  if (res.data.code === 0) {
    message.success('删除成功')
    // 刷新数据
    fetchData()
  } else {
    message.error('删除失败，' + res.data.message)
  }
}

const cancelDelete = (e: MouseEvent) => {
  message.success('取消删除')
}

const doEdit = (id: number) => {
  // todo
}
</script>

<style scoped>
.userSearchForm {
  display: flex;
  margin: auto;
}
</style>
